"""
# 处理计数 -> 区间量化（分箱）
"""
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import json
import numpy as np


def hist_plot(data, col, xlabel, ylabel, save_name, binning_mode=None):
    # 绘制收听次数直方图
    sns.set_style('whitegrid')
    fig, ax = plt.subplots()
    if binning_mode == 'divide':
        np.floor_divide(data[col], 10).hist(ax=ax, bins=100)
    elif binning_mode == 'log':
        np.floor(np.log10(data[col])).hist(ax=ax, bins=100)
    elif binning_mode == 'deciles':
        pd.qcut(data[col], 10, labels=False, duplicates='drop').hist(ax=ax, bins=100)
    else:
        data[col].hist(ax=ax, bins=100)
    ax.set_yscale('log')
    ax.tick_params(labelsize=14)
    ax.set_xlabel(xlabel, fontsize=14)
    ax.set_ylabel(ylabel, fontsize=14)
    plt.savefig(save_name)
    plt.show()


# 加载商家数据
with open('../数据集/yelp_academic_dataset_business.json') as biz_file:
    biz_df = pd.DataFrame([json.loads(x) for x in biz_file.readlines()])
# 绘制点评数量直方图
hist_plot(biz_df, 'review_count', 'Review Count', 'Occurrence', './可视化/点评数量直方图.png')
# 通过除法映射到间隔均匀的分箱中，每个分箱的取值范围都是0~9
hist_plot(biz_df, 'review_count', 'Review Count', 'Occurrence', './可视化/点评数量直方图_固定宽度分箱_除法映射.png', 'divide')
# 通过对数函数映射到指数宽度分箱
hist_plot(biz_df, 'review_count', 'Review Count', 'Occurrence', './可视化/点评数量直方图_固定宽度分箱_对数映射.png', 'log')
# 分位数分箱
hist_plot(biz_df, 'review_count', 'Review Count', 'Occurrence', './可视化/点评数量直方图_分位数分箱.png', 'deciles')
